package com.lagou.rpc.consumer.client;

import com.lagou.rpc.consumer.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;

import java.util.concurrent.*;

/**
 * 客户端
 * 1、连接Netty服务端
 * 2、提供给调用者主动关闭资源的方法
 * 3、提供消息发送的方法
 */
public class RpcClient{

    private NioEventLoopGroup group;
    private Channel channel;

    private String ip;
    private int port;

    private RpcClientHandler rpcClientHandler = new RpcClientHandler();
    //线程池实现启动某类接口为线程的类
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        initClient();
    }

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    /**
     * 初始化方法--连接Netty服务端
     */
    public void initClient(){
        try {
            //1、创建线程组
            group = new NioEventLoopGroup();
            //2、创建启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3、设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE,Boolean.TRUE)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //添加handler处理类
                            //todo
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            //5、连接Netty服务端
            channel = bootstrap.connect(ip, port).sync().channel();
            System.out.println("------------------------客户端地址："+channel.localAddress().toString().substring(1)+"-----------------------------");
        } catch (Exception e) {
            e.printStackTrace();
            if (channel!=null){
                channel.close();
            }
            if (group!=null){
                group.shutdownGracefully();
            }
        }
    }

    /**
     * 提供给调用者主动关闭资源的方法
     */
    public void close(){
        if (channel!=null){
            channel.close();
        }
        if (group!=null){
            group.shutdownGracefully();
        }
    }

    /**
     * 提供消息发送的方法
     */
    public Object send(String msg) throws ExecutionException, InterruptedException {
        rpcClientHandler.setRequestMsg(msg);
        Future future = executorService.submit(rpcClientHandler);
        return future.get();
    }


    //资源关闭方法
   /* public void destroy() throws Exception {
        close();
    }*/
}
